package com.lhd.qd.common.util;

import com.lhd.qd.common.consts.CommonConsts;
import com.lhd.qd.common.consts.RedisConsts;
import com.lhd.qd.module.system.user.model.converter.AbstractUserConverter;
import com.lhd.qd.module.system.user.model.vo.UserCacheVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Slf4j
@Component
public class UserUtils {

    public static Long getId() {
        return TokenUtils.parse(getToken());
    }

    public static UserCacheVO getUser() {

        Map<Object, Object> map = RedisUtils.hashEntries(RedisConsts.KEY_USER_INFO + getId());
        return AbstractUserConverter.INSTANCE.map2CacheVO(map);
    }

    public static String getToken() {
        try {
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            return request.getHeader(CommonConsts.REQUEST_HEADER_TOKEN_KEY);
        }
        catch (Exception e) {
            log.debug("获取HTTP请求异常", e);
        }
        return null;
    }
}
